package com.example.filters;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 一个简单的日志记录过滤器
 */
public class LoggingFilter implements Filter {

    @Override
    public void init(FilterConfig fConfig) throws ServletException {
        // 过滤器初始化时调用，通常是空的
        System.out.println("LoggingFilter 初始化完成。");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 将通用的 ServletRequest 转换为更具体的 HttpServletRequest
        HttpServletRequest req = (HttpServletRequest) request;

        String uri = req.getRequestURI();
        String ip = req.getRemoteAddr();
        
        // --- 请求到达目标资源前的处理代码 ---
        System.out.println("======================================================");
        System.out.println("请求日志：一个请求已到达！");
        System.out.println("访问时间: " + new Date());
        System.out.println("访问者IP: " + ip);
        System.out.println("请求的资源URI: " + uri);
        System.out.println("======================================================");

        // 调用 chain.doFilter() 将请求传递给下一个过滤器或目标资源
        // 这是过滤器的核心，如果没有这行代码，请求将被拦截在此处，无法继续
        chain.doFilter(request, response);

        // --- 响应从目标资源返回后的处理代码 ---
        System.out.println(uri + " 的响应已经完成。");
    }

    @Override
    public void destroy() {
        // 过滤器销毁时调用，通常是空的
        System.out.println("LoggingFilter 已销毁。");
    }
}